package de.haw.HES.Switch;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import de.haw.HES.Switch.pub.Monitor;

public class DefaultMonitor extends Thread implements Monitor {
	
	HashMap<String, AvailabilityToken> servers = new HashMap<String, AvailabilityToken>();

	@Override
	public void receiveAliveMessage(String identifier) {
		if(servers.containsKey(identifier)) {
			AvailabilityToken availabilityToken = servers.get(identifier);
			availabilityToken.setAvailable(true);
			availabilityToken.setLastOnlineTime(new Timestamp(System.currentTimeMillis()));
			servers.put(identifier, availabilityToken);
		} else {
			AvailabilityToken newToken = new AvailabilityToken();
			newToken.setAvailable(true);
			newToken.setLastOnlineTime(new Timestamp(System.currentTimeMillis()));
			servers.put(identifier, newToken);
		}
	}
	
	private void updateServers() {
		for(Entry<String,AvailabilityToken> e : servers.entrySet()) {
			AvailabilityToken value = (AvailabilityToken) e.getValue();
			AvailabilityToken lastOnline = value;
			Timestamp time = lastOnline.getLastOnlineTime();
			long timeMillis = time.getTime();
			if(timeMillis-System.currentTimeMillis() > 5000) {
				lastOnline.setAvailable(false);
				servers.put((String)e.getKey(),lastOnline);
			}
		}
	}
	
	public void run() {
		while(true) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			updateServers();
		}
	}

	@Override
	public List<String> getServersAlive() {
		List<String> result = new ArrayList<String>();
		result.add("Test");
		result.add("Test2");
		
		return result;
	}

}
